import re

class Issue:
    targetType = "issue"
    commit = "评论"
    def __init__(self, title, url, *args):
        if len(args) == 0:
            soup = getSoup(url)
            self.no = getIssueNo(soup)
            self.title = title
            self.url = url
            self.state = getIssueState(soup)
            self.cve_id = getCVE(soup)
            self.targetId = getIssueTargetId(soup)
        else:
            self.no = args[0]
            self.title = title
            self.url = url
            self.state = args[1]
            self.cve = args[2]
            self.targetId = args[3]
    # 定义一个类方法，用于创建一个实例
    @classmethod
    def create(cls, no, title, url, state, cve, targetId):
        return cls(title, url, no, state, cve, targetId)
    @classmethod
    def getStateOfIssue(cls, url):
        soup = getSoup(url)
        return getIssueState(soup)
    def __str__(self):
         return "Issue('no':{}, 'title':{}, 'url':{}, 'state':{}, 'cve':{}, 'targetId':{})".format(self.no, self.title, self.url, self.state, self.cve, self.targetId)
 

from common import *
import urllib.parse as parse
class State:
    todo = '待办的'
    confirmed = '已确认'
    technical_review = '技术评审中'
    fixing = '修复中'
    accepting = '验收中'
    completed = '已完成'
    canceled = '已取消'
    refused = '已拒绝'
    suspended = '挂起'
state2no = {'待办的': 877565,
 '已确认': 877569,
 '技术评审中': 1244182,
 '修复中': 877573,
 '验收中': 877572,
 '已完成': 877567,
 '已取消': 877574,
 '已拒绝': 877568,
 '挂起': 1244183}
def modifyIssueState(issue_no, state):
    self_headers = headers.copy()
    self_headers['X-CSRF-Token'] = 'Ugt/VwdF70kFrzF3Qd17VuO04TUR8BAcKNL1bQSFZUIIZjt/HUfydLb1NYmYhLL2Sp4VZa5r38C9bLMHHOsn9w=='
    self_headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'
    data = 'issue%5Bissue_state_id%5D={}'.format(state2no[state])
    # 如果no 以 #开头
    if str(issue_no).startswith('#'):
        issue_no = str(issue_no)[1:]
    return requests.put('https://gitee.com/openharmony/kernel_linux_5.10/issues/{}.json'.format(issue_no), headers=self_headers, proxies=proxies, data=data)
# comment delete_comment
def commentOnIssue(target_id, comment):
    if comment == '':
        assert False
    self_headers = headers.copy()
    self_headers['X-CSRF-Token'] = 'Ugt/VwdF70kFrzF3Qd17VuO04TUR8BAcKNL1bQSFZUIIZjt/HUfydLb1NYmYhLL2Sp4VZa5r38C9bLMHHOsn9w=='
    # headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'
    # headers['user-agent'] = 'PostmanRuntime/7.41.2'
    self_headers['Accept'] = '*/*;q=0.5, text/javascript, application/javascript, application/ecmascript, application/x-ecmascript'
    # headers['Connection'] = 'keep-alive'
    # headers['accept-encoding'] = 'gzip, deflate, br'
    # cookies = "oschina_new_user=false; gitee-session-n=S0NoS2YrVFdIOEk4d0VQcVhkd2pvVlJuNTFGSFlPNUU1bUFhNTNha0MvZXkxU0dRd1l6aG44Q0ZzSlp6QXJyYWJGcE0yejVtQTBMS3QzMEJPSlQzNHIyVllYNTU2TkIrN25IbGNPWDhJeHBaWkozc1VhMmJkL0lFTTNlcmc2TGg0V0svQy9sTFIyRmdQMC82UnhVemVDcHQ1OSt2d1JMYVRxMmsxUWs3M0Vta1VMN0cycEJVM0MxSlA5bmVOUExGM0Vra1Q5c1VaWit4Q1VXRnE0NjN3NXN0RVozM29pQ0t0M1Vva1dEaitCS013dEp0SlJPYi9RdW8vckVGQkNnUXc0enZYbm9qTEZWaEVaOEZrQStSaXZONVVwK25PbVF6b0c4R0NkNVV3c1FCb3JsREhSdElnSHBFQSthM2tkL2dDUVBFdElwZlpvWTdCNGRidE82c2dhOWZNREVqdk1ucHRaYkNzQWFaZzNoWHB0TGV5MnVLWnVqZCtlYldUdzVDSlFLMlh5bnoxL3J2VGNwUDdJVlhaQTFNV2lWaWZBelllcFJ4d1IxUHVxa3lRc3F4MlU1NHc4MS9qQVo4T0hLZjRpc1czREVuclhVNVlmLzVpU1R3dHVtc1RJcE84QXRRWjJXc1dtYTdzNXA2TFZ2MW5uTTV3NkxBMzFwM2RJV2JteUNGc25zdDk4dUR6eVY2VUJxRHBtYnJkWXV0QkEvOGwwSmx3T0E1V3Q3S2xUaGNqYlhhSlROZVd0UGM3b3hLV0xHb2Nzbm1yaXZJcjZ5QldTSVpiVGVSRCtpMWdoVVN3N3BuSFVCWVJuOTBGMzBVblhYNTZsZW41SXorVnIxblg2NWExdTNUbXBsbXYwWmZHakJBMG5rSGNQT05wcDFzMnhTeFdhVU5zTG89LS1MQUdZUzBwVnNYaHQ1U0ZKTzRaRkNRPT0%3D--54c4f0756d01a6e30d98de3901e8383bbf1f99a4"
    data = {
        'utf8': '✓',
        'target_type': 'issue',
        'target_id': target_id,
        'note[commit_id]': None,
        'note[line_code]': None,
        'note[noteable_id]': target_id,
        'note[noteable_type]': 'Issue',
        'note[reply_id]': None,
        'note[note]': comment,
        'commit': '评论',
    }
    return requests.post('https://gitee.com/openharmony/kernel_linux_5.10/notes', headers=self_headers , proxies=proxies, data=data)

comment_set = set()
# 在发起评论的地方进行调用
def collect_comment_id(resp):
    match_text = "Notes.appendNewNote"
    start_idx = resp.text.find(match_text)
    comment_id = resp.text[start_idx + len(match_text) + 1: start_idx + len(match_text) + 1 + 8]
    comment_set.add(comment_id)
def collectCIComment(resp, _comment_set):
    match_text = "Notes.appendNewNote"
    start_idx = resp.text.find(match_text)
    comment_id = resp.text[start_idx + len(match_text) + 1: start_idx + len(match_text) + 1 + 8]
    _comment_set.add(comment_id)
def collectHistoryComment(resp, _comment_set):
    match_text = "Notes.appendNewNote"
    start_idx = resp.text.find(match_text)
    comment_id = resp.text[start_idx + len(match_text) + 1: start_idx + len(match_text) + 1 + 8]
    _comment_set.add(comment_id)

def delete_comment(comment_id):
    self_headers = headers.copy()
    self_headers['X-CSRF-Token'] = 'Ugt/VwdF70kFrzF3Qd17VuO04TUR8BAcKNL1bQSFZUIIZjt/HUfydLb1NYmYhLL2Sp4VZa5r38C9bLMHHOsn9w=='
    # headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'
    # headers['user-agent'] = 'PostmanRuntime/7.41.2'
    self_headers['Accept'] = '*/*;q=0.5, text/javascript, application/javascript, application/ecmascript, application/x-ecmascript'
    return requests.delete('https://gitee.com/openharmony/kernel_linux_5.10/notes/{}'.format(comment_id), headers=self_headers, proxies=proxies)


def getIssueBaseInfo(url):
    soup = getSoup(url=url)
    urls = soup.find_all("a", class_="title")
    urls = [{'title': item['title'], 'url':"https://gitee.com/"+item["href"] } for item in urls]
    return urls

# 获取某一个gitee page的所有issue，以Issue类列表的形式返回
def getIssueList(url, filter = None):
    issue_list = []
    for item in getIssueBaseInfo(url):
        iss = Issue(item['title'], item['url'])
        # print(iss)
        if filter is not None:
            if filter(iss):
                issue_list.append(iss)
        else:
            issue_list.append(iss)
    return issue_list
def getNoOpenStateIssueList(url):
    issue_list = []
    for item in getIssueBaseInfo(url):
        iss = Issue(item['title'], item['url'])
        if iss.state != "待办的":
            issue_list.append(iss)
    return issue_list
# 过滤issue的title不是以[Bug]开头的issue
def filterNotBugIssue(issue):
    return not issue.title.startswith("[Bug]") and not issue.title.startswith("[新需求]")
def filterUnRelatedIssue(issue):
    return not filterNotBugIssue(issue)
import threading
issue_list_lock=threading.Lock()
def work(url, issue_list):
    res=getIssueList(url, filterNotBugIssue)
    issue_list_lock.acquire()
    issue_list.extend(res)
    issue_list_lock.release()
def fillInIssueList(urls, issue_list):
    threads = []
    for url in urls:
        # work = lambda: (print('extend'))
        t = threading.Thread(target=work(url, issue_list))
        threads.append(t)
        t.start()
        # issue_list.extend(getIssueList(url, filterNotBugIssue))
    for t in threads:
        t.join()
import sqlite3
import sys
sys.path.append("..")
import dao.IssueDao as IssueDao 
# 默认为全部状态
def get_issue_list_from_db(state=None):
    issue_list = []
    with sqlite3.connect('../dao/cve_process.db') as conn:
        issue_tup = IssueDao.get_issues(conn, state)
        for item in issue_tup:
            issue_list.append(Issue.create(item[0], item[1], item[2], item[3], item[4], item[5]))
    return issue_list

def getIssueState(soup): 
    return soup.find(id="issue-state-label").get_text(strip=True)
def getIssueNo(soup): 
    return soup.find(id="issue-number-button").get_text(strip=True)
def getIssueTargetId(soup):
    return soup.find(id="target_id")['value']
def getCVE(soup): # 从issue的描述中获取CVE编号
    s = set([tag for tag in soup.find_all("div", class_="git-issue-description markdown-body")])
    cve = re.search("CVE-\d{4}-\d{4,7}", s.pop().text)
    if  (cve is None):
        return None
    return cve.group()

def searchIssueByKeyword(keyword):
    url = "https://gitee.com/openharmony/kernel_linux_5.10/issues?utf8=%E2%9C%93\
    &state=all&issue_search={}".format(parse.quote(keyword))
    return getNoOpenStateIssueList(url)
def searchIssuesByCVE(cve):
    return searchIssueByKeyword(cve)
def getHistoryIssueList(cve): # only return 不是代办的 issues，otherwise return []
    l = searchIssuesByCVE(cve)
    ret = []
    for item in l:
        if(item.state != "待办的"):
            ret.append(item)
    return ret